﻿using System.Web.Mvc;
using System.Web.Routing;
using Kym.Core;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using Rhino.Commons.HttpModules;

namespace Kym.Web
{
    public class GlobalApplication : UnitOfWorkApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Messages", action = "List", id = ""} // Parameter defaults
                );
        }

        public GlobalApplication()
        {
            PreRequestHandlerExecute += (sender, e) => CheckAndResetDatabase();
        }

        public override void UnitOfWorkApplication_BeginRequest(object sender, System.EventArgs e)
        {
            base.UnitOfWorkApplication_BeginRequest(sender, e);

            CheckAndResetDatabase();
        }

        private void CheckAndResetDatabase()
        {
            if (Request["resetDb"] == "1")
                new SchemaExport(new Configuration().Configure().AddAssembly(typeof(Message).Assembly)).Execute(false, true, false, false);
        }

        public override void Application_Start(object sender, System.EventArgs e)
        {
            base.Application_Start(sender, e);
            InitializeMvc();
        }

        private static void InitializeMvc()
        {
            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(typeof (KymControllerFactory));
        }
    }
}